from util.selenium.webdriver.common.by import By

from base.BaseMethod import BM
from util.DataQuery.DbTools import DbTools
from util.DataQuery.FormDataDecorator import FormDataDecorator
from util.g import g


class WriteRDForm():
    form_btn_loc = (By.LINK_TEXT, '企业研究开发活动情况表')
    title_loc = (By.CSS_SELECTOR, 'h2.text-center')
    content_iframe_loc = (By.CSS_SELECTOR, "#innocomFrame")
    #    添加按钮
    # add_btn_loc = (By.CSS_SELECTOR, '.form-group.pull-right .blue')
    add_btn_loc = (By.XPATH, "//div[@class='form-group pull-right']/button[contains(string(), '添加')]")
    #    删除按钮
    # delete_btn_loc = (By.CSS_SELECTOR, '.table-search div:nth-of-type(2) button')
    delete_btn_loc = (By.XPATH, "//div[@class='form-group pull-right']/button[contains(string(), '删除')]")

    rd_id_loc = (By.CSS_SELECTOR, 'input#hcod')
    rd_name_loc = (By.CSS_SELECTOR, 'input#yproductName')
    rd_start_date_js_str = "document.getElementById('dataEprPQzsj').removeAttribute('readonly')"
    rd_end_date_js_str = "document.getElementById('dataEprPJssj').removeAttribute('readonly')"
    rd_start_date_loc = (By.CSS_SELECTOR, 'input#dataEprPQzsj')
    rd_end_date_loc = (By.CSS_SELECTOR, 'input#dataEprPJssj')
    # 技术领域
    # rd_domain1_loc = (By.CSS_SELECTOR, 'select#onemain')
    rd_domain1_loc = (By.CSS_SELECTOR, '#uniform-onemain select')
    # rd_domain2_loc = (By.CSS_SELECTOR, 'select#scdmain')
    rd_domain2_loc = (By.CSS_SELECTOR, '#uniform-scdmain select')
    # rd_domain3_loc = (By.CSS_SELECTOR, 'select#thdmain')
    rd_domain3_loc = (By.CSS_SELECTOR, '#uniform-thdmain select')

    # # # # # 技术来源 ###### 字典值 tech_source
    rd_source_loc = (By.CSS_SELECTOR, 'select#jslyList')
    rd_ipr_ids_loc = (By.CSS_SELECTOR, 'select#PZscqbha')
    rd_ipr_ids_value_loc = (By.CSS_SELECTOR, 'textarea#yxPZscqbha')
    rd_ipr_ids_value_js_str = "document.getElementById('yxPZscqbha').removeAttribute('readonly')"
    # # 研发经费总预算
    rd_budget_loc = (By.CSS_SELECTOR, 'input#spending')
    rd_spendtotal_loc = (By.CSS_SELECTOR, 'input#yfjfzzc')
    rd_spendst_loc = (By.CSS_SELECTOR, 'input#zc1')
    rd_spendnd_loc = (By.CSS_SELECTOR, 'input#zc2')
    rd_spendrd_loc = (By.CSS_SELECTOR, 'input#zc3')
    # 最后面的三个 textarea
    rd_ooim_loc = (By.CSS_SELECTOR, 'textarea#PLxmd')
    rd_cti_loc = (By.CSS_SELECTOR, 'textarea#PHxjs')
    rd_pra_loc = (By.CSS_SELECTOR, 'textarea#PQdcg')
    upload_btn_loc = (By.CSS_SELECTOR, '.uploadAttachment a')
    # 保存、返回按钮位置
    save_btn_loc = (By.CSS_SELECTOR, '.box-footer.text-right #dataEprsave')
    back_btn_loc = (By.CSS_SELECTOR, '.box-footer.text-right .btn-default')

    next_page_loc = (By.CSS_SELECTOR, ".pagination.pull-right li:nth-of-type(4) a")

    page_num_loc = (By.CSS_SELECTOR, ".pagination.pull-right li:nth-of-type(3) a")
    select_all_loc = (By.CSS_SELECTOR, "input#items_selector")

    delete = False

    # 写代码时方便提示, 基本方法完成后删除
    def __init__(self, driver=None):
        self.driver = driver
        setattr(g, self.class_name, list())

    @property
    def class_name(self):
        return self.__class__.__name__

    def input_rd_info(self, rd_id='', rd_name='', start_date='', end_date=''):
        # start_date = self.handel_date(start_date)
        # end_date = self.handel_date(end_date)
        rd_id = str(rd_id).zfill(2)
        BM.input(ele_loc=self.rd_id_loc, driver=self.driver, keys=rd_id)
        BM.input(ele_loc=self.rd_name_loc, driver=self.driver, keys=rd_name)
        self.driver.execute_script(self.rd_start_date_js_str)
        BM.input(ele_loc=self.rd_start_date_loc, driver=self.driver, keys=start_date)
        self.driver.execute_script(self.rd_end_date_js_str)
        BM.input(ele_loc=self.rd_end_date_loc, driver=self.driver, keys=end_date)

    @classmethod
    def get_domain_by_namelist(cls, hitech_field_namelist=""):
        return hitech_field_namelist.split(",")

    def input_tech_info(self, tech_fieldname='', tech_fieldlist="", tech_source='', ipr_ids=''):
        try:
            if not tech_fieldname:
                hitech_fields = DbTools.get_hitech_name_by_ids(ids=tech_fieldlist)
                hitech_ = {i.get("id"): i.get("name") for i in hitech_fields}
                tech_fieldname = ",".join([hitech_.get(int(i)) for i in tech_fieldlist.split(",")])
            domain_num = len(tech_fieldname.split(","))
            domain1, domain2, domain3, domain4 = None, None, None, None
            if domain_num == 2:
                domain1, domain2 = self.get_domain_by_namelist(hitech_field_namelist=tech_fieldname)
                domain3 = "无"
                tech_fieldname += ",无"
            if domain_num == 3:
                domain1, domain2, domain3 = self.get_domain_by_namelist(hitech_field_namelist=tech_fieldname)
            elif domain_num == 4:
                domain1, domain2, domain3, domain4 = self.get_domain_by_namelist(hitech_field_namelist=tech_fieldname)
            BM.select_domain(selector_loc=self.rd_domain1_loc, text_value=domain1, driver=self.driver,
                             tech_fieldname=tech_fieldname)
            BM.select_domain(selector_loc=self.rd_domain2_loc, text_value=domain2, driver=self.driver,
                             tech_fieldname=tech_fieldname)
            BM.select_domain(selector_loc=self.rd_domain3_loc, text_value=domain3, driver=self.driver,
                             tech_fieldname=tech_fieldname)

            BM.select_value_choice(selector_loc=self.rd_source_loc, text_value=tech_source, driver=self.driver)

            self.driver.execute_script(self.rd_ipr_ids_value_js_str)
            # 将字符串按 , 切割， 然后将每个元素前加 IP 然后用 \n 拼接
            # ipr_ids_str = '\n'.join(["IP" + i.zfill(2) for i in ipr_ids.split(',') if i])
            # BM.input(ele_loc=self.rd_ipr_ids_value_loc, driver=self.driver, keys=ipr_ids_str)
            if ipr_ids == "":
                return
            for ip in ipr_ids.split(","):
                ip_s = "IP" + ip.zfill(2) if ip != "0" else "其他"
                BM.select_value_choice(selector_loc=self.rd_ipr_ids_loc, driver=self.driver, text_value=ip_s)
        except Exception as err:
            msg = "error: {} file: {} lines: {}".format(err,
                                                        err.__traceback__.tb_frame.f_globals[
                                                            "__file__"],
                                                        err.__traceback__.tb_lineno)
            g.logger.error(msg)
            raise Exception(msg)

    # 经费信息填写
    def input_expenditure_info(self, rd_budget='', rd_spend1styear='', rd_spend2ndyear='', rd_spend3rdyear=''):
        BM.input(ele_loc=self.rd_budget_loc, driver=self.driver, keys=rd_budget)
        BM.input(ele_loc=self.rd_spendst_loc, driver=self.driver, keys=rd_spend1styear)
        BM.input(ele_loc=self.rd_spendnd_loc, driver=self.driver, keys=rd_spend2ndyear)
        BM.input(ele_loc=self.rd_spendrd_loc, driver=self.driver, keys=rd_spend3rdyear)

    # # # # # #  这里输入数据有问题， 往一个输入框中输入数据时， 他会把数据截开输入到三个输入框中， 未知 BUG。   completed
    def input_desc_info(self, ooim='', cti='', pra=''):
        BM.input_textarea_info(ele_loc=self.rd_ooim_loc, driver=self.driver, keys=ooim)
        BM.input_textarea_info(ele_loc=self.rd_cti_loc, driver=self.driver, keys=cti)
        BM.input_textarea_info(ele_loc=self.rd_pra_loc, driver=self.driver, keys=pra)

    def click_save_btn(self):
        return BM.global_click_btn(btn_loc=self.save_btn_loc, driver=self.driver)

    @FormDataDecorator
    def main(self, rd_id='', rd_name='', start_date='', end_date='',
             tech_fieldname='', tech_fieldlist="", tech_source='', ipr_ids='',
             rd_budget='', rd_spend1styear='', rd_spend2ndyear='', rd_spend3rdyear='',
             ooim='', cti='', pra=''):
        # # 在这里判断 rd_name 是否是 党志恒 ， 如果是， 将 g 变量的 is_continue 属性置为 True , 并且直接返回;
        # if rd_name == '党志恒':
        #     g.is_continue = True
        #     return
        # if g.is_first_entry and self.delete:
        #     BM.click(driver=self.driver, ele_loc=self.form_btn_loc)
        #     BM.delete_all(driver=self.driver, page_num_loc=self.page_num_loc, select_all_loc=self.select_all_loc, delete_btn_loc=self.delete_btn_loc)
        #     self.delete = True
        try:
            is_click = False
            class_name = self.class_name
            if getattr(g, class_name) == []:
                is_click = True
                BM.click(driver=self.driver, ele_loc=self.form_btn_loc)
                BM.cut_over_frame(driver=self.driver, selector_loc=self.content_iframe_loc)
                a_list = getattr(g, class_name)
                table_loc = (By.CSS_SELECTOR, ".tableBody")
                tr_loc = (By.CSS_SELECTOR, ".tableBody tr td:nth-of-type(3)")

                while True and g.repetition:
                    BM.wait(driver=self.driver, ele_loc=table_loc)
                    data = self.driver.find_elements(*tr_loc)
                    for i in data:
                        # 获取 标签中的 汉字
                        rd_name_str = i.text
                        a_list.append(rd_name_str)

                    next_btn = BM.get_ele(driver=self.driver, ele_loc=self.next_page_loc)
                    onclick = next_btn.get_attribute("onclick")
                    if not onclick:
                        # BM.click(driver=self.driver, ele_loc=self.next_page_loc)
                        break
                    else:
                        next_btn.click()
            li_list = getattr(g, class_name)
            if rd_name.strip() in li_list and g.repetition:
                g.logger.info("{} ----- {} 已存在".format(class_name, rd_name))
                return
            g.logger.info("{}： {}".format(class_name, li_list))
            # if not is_click:
            #     BM.click(driver=self.driver, ele_loc=self.form_btn_loc)
            # if g.repetition and not self.delete:
            #     BM.delete_all(driver=self.driver, page_num_loc=self.page_num_loc, select_all_loc=self.select_all_loc, delete_btn_loc=self.delete_btn_loc)
            #     self.delete = True

            BM.click(driver=self.driver, ele_loc=self.add_btn_loc)
            BM.wait(driver=self.driver, ele_loc=self.save_btn_loc)
            self.input_rd_info(rd_id=rd_id, rd_name=rd_name, start_date=start_date, end_date=end_date)
            self.input_tech_info(tech_fieldname=tech_fieldname, tech_fieldlist=tech_fieldlist, tech_source=tech_source,
                                 ipr_ids=ipr_ids)
            self.input_expenditure_info(rd_budget=rd_budget, rd_spend1styear=rd_spend1styear,
                                        rd_spend2ndyear=rd_spend2ndyear, rd_spend3rdyear=rd_spend3rdyear)
            self.input_desc_info(ooim=ooim, cti=cti, pra=pra)

            # # # TODO 上传附件
            BM.click_upload_attach(btn_loc=self.upload_btn_loc, driver=self.driver, class_name=self.class_name,
                                   _id=rd_id)
            res = self.click_save_btn()
            if res:
                li_list.append(rd_name)
        except Exception as err:
            msg = "error: {} file: {} lines: {}".format(err,
                                                        err.__traceback__.tb_frame.f_globals[
                                                            "__file__"],
                                                        err.__traceback__.tb_lineno)
            g.logger.error(msg)
            raise Exception(msg)
        # self.wait(btn_loc=self.back_btn_loc)
        # click_back_btn(btn_loc=self.back_btn_loc, driver=self.driver)
